package com.doudou.collection.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName SecurityConfig
 * @Description Security框架配置类
 * @Author blue sky
 * @Date 2023/6/1 23:17
 * @Version 1.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //配置密码加密的方式
    @Bean
    public PasswordEncoder passwordEncoder() {
        //返回此加密的编码器之后, 用户输入的密码
        //会通过此编码器加密之后再和数据库里面的密码进行比较
        return new BCryptPasswordEncoder();
    }

    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //当访问需要登录认证才能访问的资源时, 没有登录的时跳转到登录页面
        http.formLogin().loginPage("/login.html");
        //设置黑名单(需要登录才可访问的资源)
        String[] urls = {};
        http.authorizeHttpRequests()  //对请求进行授权
                .mvcMatchers(urls)    //匹配某些路径
                .authenticated()      //需要通过登录认证
                .anyRequest()         //其它任意请求
                .permitAll();         //直接放行, 即不需要登录也可以访问

        //关闭跨域攻击防御策略
        http.csrf().disable();
    }
}
